var express = require('express');
var router = express.Router();
var db = require('../public/javascripts/db');

/* GET users listing. */
function countAge(time) {
    if (!time) {
        return null;
    } else {
        var year = new Date().getFullYear();
        var month = new Date().getMonth() + 1;
        var date = new Date().getDate();
        var data = time.split('-');
        var age = year - data[0];
        if (month < data[1]) {
            return age - 1
        } else if (month == data[1]) {
            if (date < data[2]) {
                return age - 1;
            } else {
                return age;
            }
        } else {
            return age;
        }
    }
}

router.get('/', function (req, res, next) {
    console.log(req.query.identify_num)
    var sql = 'SELECT * FROM users WHERE identify_num = ?';
    db.query(sql, req.query.identify_num, (err, result) => {
        console.log('user result', result);
        var len = result.length;
        res.send({status: 2, data: result[len - 1]})
    })
});

router.post('/', function (req, res) {
    var data = req.body.info;
    console.log(req.body);
    // var sql = "INSERT INTO 'users' " +
    //     "(phone,name,identify_num,gender,age,birth_place,birth_date,medical_history,locked) " +
    //     "VALUES (?,?,?,?,?,?,?,?,?)";
    var sql = "INSERT INTO `users`" +
        "(phone,name,identify_num,gender,age,birth_place,birth_date,medical_history,locked) " +
        "VALUES (?,?,?,?,?,?,?,?,?) ";
    var age = countAge(data.birth_date);
    var sqlParams = [data.telephone, data.name, data.identify_num, data.gender, age,
        data.birth_place, data.birth_date, data.medical_history, false];
    db.query(sql, sqlParams, (err, result) => {
        if (err) {
            throw err;
            return;
        } else {
            console.log('result users insertid 1111111', result)
            res.send({data: result.insertId})
        }
    })
})

router.put('/', function (req, res) {
    var data = req.body.info;
    console.log(req.body);
    var sql = "UPDATE users SET phone = ?,name = ?,identify_num = ?,gender = ?,age = ?," +
        "birth_place = ?,birth_date = ?,medical_history = ?,locked = ? WHERE id = ?";
    var age = countAge(data.birth_date);
    var sqlParams = [data.telephone, data.name, data.identify_num, data.gender, age,
        data.birth_place, data.birth_date, data.medical_history, false, data.owner_id];
    db.query(sql, sqlParams, (err, result) => {
        if (err) {
            throw err;
            return;
        } else {
            console.log('result users', result)
            res.send({data: result.insertId})
        }
    })
})

module.exports = router;
